<?php

namespace App\Http\Controllers;

use App\Article;
use App\Message;
use Illuminate\Http\Request;

use App\Http\Requests;

use App\Comment;

class CommentController extends Controller
{
    //
    public function store(Request $request)
    {
        $this->validate($request, [
            'nickname' => 'required',
            'email'=>'required',
            'website'=>'required',
            'content'=>'required|max:10',
            'article_id' => 'required',
        ]);

        $article_id = $request->get("article_id");
        $article = Article::find($article_id);
        $from = $request->get('nickname');
        $content = $request->get('content');
        $preg = '/@(\S+)\s(.*)(?!@)/';
        if (preg_match_all($preg, $content, $matches)) {
            $message = new Message();
            $message->from = $from;
            for ($i = 0; $i < count($matches[0]); $i++) {
                $message->to = $matches[1][$i];
                $message->body = $matches[2][$i];
                $message->article_title =  $article->title;
                $message->article_id =  $article->id;
                if ($message->save()) {
                    if (Comment::create($request->all())) {
                        return redirect()->back();
                    }
                }
                $message->isread = 0;
            }
        } else {
            if (Comment::create($request->all())) {
                return redirect()->back();
            }else {
                return redirect()->back()->withInput()->withErrors("评论发表失败!");
            }
        }
    }
}
